package com.example.dao.impl;

import com.example.dao.UserDao;
import com.example.model.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import com.example.utils.JDBCUtils;
import org.springframework.stereotype.Repository;

import java.util.List;


public class UserDaoImpl implements UserDao {
    JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    /**
     * 新增一个用户
     * @param user
     */
    @Override
    public void addUser(User user) {
        String sql = "insert into user (" +
                "username ,password , email , name , telephone , sex , birthday) values ( ? , ? , ? , ? , ? , ? , ?)";
        int update = template.update(sql,
                user.getUsername(),
                user.getPassword(),
                user.getEmail(),
                user.getName(),
                user.getTelephone(),
                user.getSex(),
                user.getBirthday());
        if (update <= 0) {
            System.out.println("dao 层错误");
        }
    }

    /**
     * 根据用户名查询用户是否存在
     * @param username
     * @return
     */
    public User findUserByUsername(String username) {
        String sql = "select * from user where username = ?";
        List<User> users = template.query(sql, new BeanPropertyRowMapper<User>(User.class),username);
        if (users == null || users.size() == 0) {
            // 用户不存在
            return null;
        }else {
            return users.get(0);
        }
    }

    @Override
    public User findUserByUnameAndPass(String username, String password) {
        String sql = "select * from user where username = ? and password = ?";
        List<User> users = template.query(sql, new BeanPropertyRowMapper<User>(User.class),username,password);
        if (users == null || users.size() == 0) {
            // 用户不存在
            return null;
        }else {
            return users.get(0);
        }
    }
}
